/*
 * @Author: wrngygy
 * @Date: 2025-07-01
 * @Description: 路由工具函数
 */

import type { RouteRecordRaw } from 'vue-router'
import type { AppRouteRecordRaw, MenuItem } from './types'

/**
 * 将路由转换为菜单项
 * @param routes 路由配置
 * @param permissions 用户权限
 * @returns 菜单项数组
 */
export function routesToMenus(
	routes: AppRouteRecordRaw[],
	permissions: string[] = []
): MenuItem[] {
	const menus: MenuItem[] = []

	routes.forEach((route) => {
		// 跳过隐藏的路由
		if (route.meta?.hidden) {
			return
		}

		// 检查权限
		if (route.meta?.permissions) {
			const hasPermission = route.meta.permissions.some(permission =>
				permissions.includes(permission)
			)
			if (!hasPermission) {
				return
			}
		}

		const menu: MenuItem = {
			id: route.name as string,
			title: route.meta?.title || route.name as string,
			path: route.path,
			icon: route.meta?.icon,
			sort: route.meta?.sort || 0,
			permission: route.meta?.permissions?.[0],
			externalLink: route.meta?.externalLink
		}

		// 处理子路由
		if (route.children && route.children.length > 0) {
			const childMenus = routesToMenus(route.children, permissions)
			if (childMenus.length > 0) {
				menu.children = childMenus
			}
		}

		menus.push(menu)
	})

	// 按排序字段排序
	return menus.sort((a, b) => (a.sort || 0) - (b.sort || 0))
}

/**
 * 扁平化路由
 * @param routes 路由配置
 * @returns 扁平化的路由数组
 */
export function flattenRoutes(routes: AppRouteRecordRaw[]): AppRouteRecordRaw[] {
	const flattened: AppRouteRecordRaw[] = []

	function flatten(routes: AppRouteRecordRaw[]) {
		routes.forEach((route) => {
			flattened.push(route)
			if (route.children && route.children.length > 0) {
				flatten(route.children)
			}
		})
	}

	flatten(routes)
	return flattened
}

/**
 * 根据路由名称查找路由
 * @param routes 路由配置
 * @param name 路由名称
 * @returns 找到的路由或 undefined
 */
export function findRouteByName(
	routes: AppRouteRecordRaw[],
	name: string
): AppRouteRecordRaw | undefined {
	const flattened = flattenRoutes(routes)
	return flattened.find(route => route.name === name)
}

/**
 * 根据路径查找路由
 * @param routes 路由配置
 * @param path 路由路径
 * @returns 找到的路由或 undefined
 */
export function findRouteByPath(
	routes: AppRouteRecordRaw[],
	path: string
): AppRouteRecordRaw | undefined {
	const flattened = flattenRoutes(routes)
	return flattened.find(route => route.path === path)
}

/**
 * 获取面包屑导航
 * @param routes 路由配置
 * @param currentPath 当前路径
 * @returns 面包屑数组
 */
export function getBreadcrumbs(
	routes: AppRouteRecordRaw[],
	currentPath: string
): MenuItem[] {
	const breadcrumbs: MenuItem[] = []
	const pathSegments = currentPath.split('/').filter(Boolean)
	
	let currentRoutes = routes
	let currentPathBuild = ''

	pathSegments.forEach((segment) => {
		currentPathBuild += `/${segment}`
		
		const route = currentRoutes.find(r => r.path === currentPathBuild)
		if (route && route.meta?.breadcrumb !== false) {
			breadcrumbs.push({
				id: route.name as string,
				title: route.meta?.title || route.name as string,
				path: route.path
			})
			
			if (route.children) {
				currentRoutes = route.children
			}
		}
	})

	return breadcrumbs
}

/**
 * 检查路由是否需要权限
 * @param route 路由配置
 * @param permissions 用户权限
 * @param roles 用户角色
 * @returns 是否有权限访问
 */
export function hasRoutePermission(
	route: AppRouteRecordRaw,
	permissions: string[] = [],
	roles: string[] = []
): boolean {
	// 检查权限
	if (route.meta?.permissions && route.meta.permissions.length > 0) {
		const hasPermission = route.meta.permissions.some(permission =>
			permissions.includes(permission)
		)
		if (!hasPermission) {
			return false
		}
	}

	// 检查角色
	if (route.meta?.roles && route.meta.roles.length > 0) {
		const hasRole = route.meta.roles.some(role =>
			roles.includes(role)
		)
		if (!hasRole) {
			return false
		}
	}

	return true
}

/**
 * 过滤有权限的路由
 * @param routes 路由配置
 * @param permissions 用户权限
 * @param roles 用户角色
 * @returns 过滤后的路由
 */
export function filterRoutesByPermission(
	routes: AppRouteRecordRaw[],
	permissions: string[] = [],
	roles: string[] = []
): AppRouteRecordRaw[] {
	return routes.filter(route => {
		const hasPermission = hasRoutePermission(route, permissions, roles)
		
		if (hasPermission && route.children) {
			route.children = filterRoutesByPermission(route.children, permissions, roles)
		}
		
		return hasPermission
	})
}

/**
 * 生成路由缓存键
 * @param route 路由配置
 * @returns 缓存键
 */
export function getRouteCacheKey(route: AppRouteRecordRaw): string {
	return route.name as string || route.path
}
